package org.tong.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.tong.bean.Student;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class StudentDao extends JdbcTemplate {

    @Autowired
    @Qualifier("systemDataSource")
    private DataSource dataSource;


    public int insert(Student student) {
        return update("insert into student (name)values(?)", student.getName());
    }

    public List<Student> queryAllStudents() {
        return query("select * from student", getRowMapper());
    }


    private RowMapper<Student> getRowMapper() {
        return new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student = new Student();
                student.setId(resultSet.getInt(1));
                student.setName(resultSet.getString(2));
                return student;
            }
        };
    }

    @Override
    public DataSource getDataSource() {
        return dataSource;
    }


}
